package com.itheima.youdianda.exceptionHandler;

import com.itheima.youdianda.common.R;
import com.itheima.youdianda.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class MyExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler (SQLIntegrityConstraintViolationException e){
        if(e.getMessage().contains("Duplicate entry")){
            log.error("mysql异常：{}", e.getMessage());
            String[] split = e.getMessage().split(" ");
            return R.error(split[2] + "已存在");
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CommonException.class)
    public R<String> commonExceptionHandler(CommonException e){
        return R.error(e.getMessage());
    }
}
